//
//  ReadViewController.m
//  liang ping
//
//  Created by lanou on 16/3/10.
//  Copyright © 2016年 孙金龙. All rights reserved.
//

#import "ReadViewController.h"
#import "ReadViewCell.h"
#import "ReadListController.h"
#import "RequestManager.h"
#import "ProductModel.h"
#import "UIImageView+WebCache.h"
@interface ReadViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UIPageControl *page;
@property(nonatomic,strong)UICollectionView *collection;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,strong)NSMutableArray *modelArray;
@property(nonatomic,strong)NSMutableArray *imageArray;

@end

@implementation ReadViewController

- (void)dealloc
{
    [self.timer invalidate];
}

- (void)requestNetwork
{
    [RequestManager requestWithUrl:@"http://api2.pianke.me/read/columns" requestType:RequestTypeGet parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = dic[@"data"];
        NSArray *array  = dataDic[@"list"];
        NSArray *arrayPic = dataDic[@"carousel"];// 轮播图的图片
        
        self.modelArray = [NSMutableArray array];
        for (NSDictionary *modelDic in array)
        {
            ProductModel *model = [[ProductModel alloc] init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.modelArray addObject:model];
        }
        self.imageArray = [NSMutableArray array];
        self.urlArray = [NSMutableArray array];
        for (NSDictionary *PicDic in arrayPic)
        {
            [self.imageArray addObject:PicDic[@"img"]];
            [self.urlArray addObject:PicDic[@"url"]];
        }
        // NSLog(@"%@",self.imageArray);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collection reloadData];
            // 放在这个位置可以刷新主线程scrollview出现才不会有延迟
            self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 61, KWidth, KHeight/4+15)];
            self.scrollView.backgroundColor = [UIColor grayColor];
            self.scrollView.contentSize = CGSizeMake(KWidth*self.imageArray.count, KHeight/4+15);
            self.scrollView.contentOffset = CGPointMake(0, 0);
            self.scrollView.delegate = self;
            self.scrollView.pagingEnabled = YES;
            for (int i = 0; i < self.imageArray.count; i++)
            {
                UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(KWidth*i, 0, KWidth, 230)];
                NSString *pic = self.imageArray[i];
                // NSLog(@"%@",pic);
                [image sd_setImageWithURL:[NSURL URLWithString:pic]];
                CGFloat red = arc4random()%(255-1+1)+1;
                CGFloat green = arc4random()%(255-1+1)+1;
                CGFloat blue = arc4random()%(255-1+1)+1;
                image.backgroundColor = [UIColor colorWithRed:red/255 green:green/255 blue:blue/255 alpha:1];
                [self.scrollView addSubview:image];
            }
            self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(KWidth-110, _scrollView.frame.size.height+15+15, 100, 20)];
            self.page.numberOfPages = self.imageArray.count;
            self.page.backgroundColor = [UIColor clearColor];
            [self.page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
            
            [self.view addSubview:self.scrollView];
            [self.view addSubview:self.page];
        });

    } error:^(NSError *error) {
        
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestNetwork];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    NSLog(@"  %f",KWidth);
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 71+KHeight/4+15, KWidth, KHeight*3/4-71-15) collectionViewLayout:layout];
    self.collection.dataSource =self;
    self.collection.delegate =self;
    self.collection.backgroundColor = [UIColor whiteColor];
    
    [self.collection registerClass:[ReadViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.view addSubview:self.collection];
    
    // 定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
}

// 定时器
- (void)timerAction
{
    static int count = 0;
        [UIView animateWithDuration:1 animations:^{
            self.scrollView.contentOffset = CGPointMake(KWidth*count, 0);
        }];
       self.page.currentPage = count;
    count++;
    if (count == self.imageArray.count)
    {
        count = 0;
    }
}

// page点击事件
- (void)pageAction:(UIPageControl *)page
{
    // self.scrollView.contentOffset = CGPointMake(KWidth*page.currentPage, 0);
    // 带滑动效果
    [self.scrollView setContentOffset:CGPointMake(KWidth*page.currentPage, 0) animated:YES];
}

// scrollview结束减速的方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 当前第几个页面选中的page就显示第几个
    self.page.currentPage = scrollView.contentOffset.x/KWidth;
}

- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 9;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ReadViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor redColor];
    cell.model = _modelArray[indexPath.row];
    return cell;
}

// 返回每个item的宽和高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((KWidth-20)/3, (_collection.frame.size.height-20)/3);
}

// 返回集合视图整体的上下左右的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

// 控制集合视图的列边距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

// 控制集合视图的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
        ReadListController *readList = [[ReadListController alloc] init];
    ProductModel *model = self.modelArray[indexPath.row];
    readList.type = model.type;
    readList.Title = model.name;
    [self presentViewController:readList animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
